import re
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QMainWindow, QMessageBox, QGraphicsScene, QFileDialog
from PyQt6.uic.properties import QtGui
from PyQt6.uic.uiparser import QtWidgets
from Database_operations import perform_login, insert_data
from Login import LoginWindow
from navigationUI import Window


class LoginWindow(QMainWindow, LoginWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

    """"登录函数设计"""

    def sign(self):
        username = self.lineEdit.text()
        password = self.lineEdit_3.text()
        if re.match(r'^\w{4,16}$', username) is None:
            QMessageBox.warning(self, "登录失败", "用户名不合规")
            return
        if re.match(r'^(?=.*[a-z])(?=.*[A-Z]).{6,16}$', password) is None:
            QMessageBox.warning(self, "登录失败", "密码不合规")
            return
        if perform_login(username, password):
            QMessageBox.information(self, "登录成功", "欢迎用户, {}".format(username))
            try:
                w = Window()
                w.show()
            except Exception as e:
                print(e)
            self.hide()  # 隐藏登录窗口
        else:
            QMessageBox.warning(self, "登录失败", "账号或密码无效")

    """slot1 和slot3 是实现stackedWidget 换页的
    """

    def slot1(self):
        self.stackedWidget.setCurrentIndex(1)

    def slot3(self):
        self.stackedWidget.setCurrentIndex(0)

    """这个函数是实现注册功能的
    """

    def slot2(self):
        username = self.lineEdit_4.text()
        password = self.lineEdit_6.text()
        if re.match(r'^\w{4,16}$', username) is None:
            QMessageBox.warning(self, "注册失败", "用户名不合规")
            return
        if re.match(r'^(?=.*[a-z])(?=.*[A-Z]).{6,16}$', password) is None:
            QMessageBox.warning(self, "注册失败", "密码不合规")
            return
        if insert_data(username, password):
            QMessageBox.information(self, "注册成功", "欢迎使用山羊手写数字识别")
            self.lineEdit_4.clear()
            self.lineEdit_6.clear()
            self.stackedWidget.setCurrentIndex(0)
        else:
            QMessageBox.warning(self, "登录失败", "用户名不合规")


def main():
    app = QApplication(sys.argv)
    login_window = LoginWindow()
    login_window.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()
